<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑线路' : '新增线路'"
    width="800"
    :close-on-click-modal="false"
    :show-close="false"
    destroy-on-close
  >
    <div class="modal-create-or-edit">
      <el-alert
        v-if="disabled"
        title="此线路未对接大屏，无法控制是否在大屏上显示"
        type="warning"
        show-icon
        style="margin: -10px 0 20px"
        :closable="false"
      />
      <el-form ref="modalFormRef" :model="modalForm" :rules="modalFormRule" label-width="100">
        <el-form-item label="线路名称" prop="name">
          <el-input v-model="modalForm.name" placeholder="请输入线路名称" />
        </el-form-item>
        <el-form-item label="色值" prop="color" class="color">
          <el-input v-model="modalForm.color" placeholder="请输入" maxlength="9" />
          <div class="color-item" :style="{ background: modalForm.color }"></div>
        </el-form-item>
        <el-form-item label="大屏显示" prop="display" v-if="!disabled">
          <el-switch v-model="modalForm.display" inline-prompt active-text="是" inactive-text="否" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="是否环线" prop="loop">
          <el-switch v-model="modalForm.loop" inline-prompt active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
      <div class="station-block">
        <StationTree :data="modalForm.station" @tree-change="setStation"></StationTree>
      </div>
    </div>
    <div class="modal-create-or-edit-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" :loading="loadingSubmit" @click="submitForm(modalFormRef)">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts" name="ModalCreateOrEdit">
import { ref, computed, reactive, onMounted } from "vue";
import StationTree from "../component/station_tree.vue";
import { editRouterApi, createRouterApi } from "@/api/modules/sysManagement/routeManage";
import { Route } from "@/api/interface/sysManagement";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

const props = defineProps({
  isEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  editItem: {
    type: Object as () => Route.ResRouteList,
    required: false,
    default: () => ({}) as Route.ResRouteList
  }
});

const emit = defineEmits(["cancel", "submit"]);

const dialogVisible = ref(false);
const loadingSubmit = ref(false);

const modalFormRef = ref<FormInstance>();
let modalForm = reactive<Route.ResRouteList>({
  name: "",
  color: "",
  display: false,
  support: false,
  station: [],
  loop: false
});
const modalFormRule = reactive<FormRules>({
  name: [
    { required: true, message: "内容不能为空", trigger: ["blur", "change"] },
    { min: 0, max: 64, message: "不超过64个字符", trigger: ["blur", "change"] }
  ],
  color: [
    {
      required: true,
      message: "请输入HEX格式的色值",
      trigger: ["blur", "change"],
      pattern: /^#([0-9a-fA-F]{3}){1,2}([0-9a-fA-F]{2})?$/
    }
  ],
  loop: [{ required: true, message: "内容不能为空", trigger: ["blur", "change"] }]
});
const disabled = computed(() => !modalForm.support);

const initialEditForm = () => {
  Object.assign(modalForm, props.editItem);
  modalForm.loop = props.editItem.loop || false;
};

const cancel = () => {
  closeDialog();
  emit("cancel");
};

const submit = () => {
  closeDialog();
  emit("submit");
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loadingSubmit.value = true;
    try {
      const station: Route.ResStationList[] = [];
      modalForm.station.filter((item, index) => {
        const list: Route.ResStationList = {
          name: item.name,
          index
        };
        if (item.id) {
          list.id = item.id;
        }
        if (props.isEdit) {
          list.route_id = props.editItem.id;
        }
        station.push(list);
      });
      modalForm.station = station;
      // 编辑
      if (props.isEdit) {
        editRouterApi(modalForm.id || 0, modalForm)
          .then(() => {
            ElMessage.success("操作成功");
            loadingSubmit.value = false;
            submit();
          })
          .catch(error => {
            loadingSubmit.value = false;
            console.error(error);
            let str = "";
            console.log(error.response);
            if (error.response && error.response.data && error.response.data.message) {
              str = error.response.data.message;
            }
            ElMessage.error("操作失败" + (str.length > 0 ? ": " + str : ""));
            // this.cancel()
          });
      } else {
        createRouterApi(modalForm)
          .then(() => {
            ElMessage.success("操作成功");
            loadingSubmit.value = false;
            submit();
          })
          .catch(error => {
            loadingSubmit.value = false;
            console.error(error);
            let str = "";
            console.log(error.response);
            if (error.response && error.response.data && error.response.data.message) {
              str = error.response.data.message;
            }
            ElMessage.error("操作失败" + (str.length > 0 ? ": " + str : ""));
            // this.cancel()
          });
      }
    } finally {
      loadingSubmit.value = false;
    }
  });
};

const setStation = (data: Route.ResStationList[]) => {
  modalForm.station = data;
};

const openDialog = () => {
  dialogVisible.value = true;
};

const closeDialog = () => {
  dialogVisible.value = false;
};

onMounted(() => {
  if (props.isEdit) {
    initialEditForm();
  }
  openDialog();
});
</script>

<style scoped lang="scss">
.modal-create-or-edit {
  .el-form {
    display: grid;
    grid-template-columns: repeat(2, 50%);
    justify-content: space-between;
  }
}
.modal-create-or-edit-footer {
  text-align: right;
}
:deep() .ant-transfer-list-body-not-found {
  img {
    display: none;
  }
}
:deep() .ant-transfer {
  .ant-btn {
    width: 24px;
    min-width: 24px;
    max-width: 24px;
    margin-right: 0;
    margin-left: 0;
  }
}
.station-block {
  width: 100%;
  height: 300px;
  padding: 0 8px;
  margin-bottom: 22px;
}
.color {
  position: relative;
  .color-item {
    position: absolute;
    right: 16px;
    width: 50px;
    height: 15px;
  }
}
</style>
